import React,{Component} from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';
import util from "@/common/util"
// import cookies from "js-cookie"
import jwt_decode from 'jwt-decode'
import layer from '@/common/layer'

class Login extends Component{
    constructor(props){
        super(props)
        this.state={
            gotoUrl:'',
            username:'',
            username_valid:true,
            password:'',
            password_valid:true
        },
        this.valids=[
            {
                key:"username",
                func(str){
                    if (str.length!==11)
                    {
                        layer.open({
                            content:"请输入正确的手机号码",
                            btn:'好的'
                        })
                        return false
                    }
                    return true
                }
            },
            {
                key:'password',
                func(str){
                    if (str.length===0)
                    {
                        layer.open({
                            content:"请输入密码",
                            btn:'好的'
                        })
                        return false
                    }
                    if (str.length<6 || str.length>16)
                    {
                        layer.open({
                            content:"密码长度必须在6个字符至16个字符",
                            btn:'好的'
                        })
                        return false
                    }
                    return true
                }
            }
        ];
        this.gotoUrl=null;
    }

    usernameChange(e){
        this.setState({
            username:e.target.value
        });
    }

    passwordChange(e){
        this.setState({
            password:e.target.value
        });
    }

    beforeLogin(){
        for (let item of this.valids){
            if (!item.func(this.state[item.key])){
                this.setState({
                    [item.key+'_valid']:false
                })
                return;
            }else{
                this.setState({
                    [item.key+'_valid']:true
                })
            }
        }

        this.login();
    }

    async login(){
        let sendObj={
            username:this.state.username,
            password:this.state.password
        }

        let rsp=await axios.post(`${util.host}/auth`,sendObj).catch((error)=>{
            if (error.response.status===403){
                layer.open({
                    content:"账户或者密码错误",
                    btn:"好的"
                })
            }
        })


        if (rsp.data.userType===2){
            localStorage.clear();
            layer.open({
                content:"暂不支持渠道登录",
                btn:'好的'
            });
            return;
        }
        /**
         * @param sub login username
         * @param iat login timestamp
         * @param exp expire timestamp
         *
         *  in javascript the timestamp is ms,you should x1000 for java timestamp
         *
         */
        let res = jwt_decode(rsp.data.token)
        res.exp = res.exp * 1000
        res.iat = res.iat * 1000
        res.token = rsp.data.token
        for (let item in res) {
          localStorage.setItem(item, res[item])
        }
        let reqUrl = rsp.data.userType === 1 ? '/user/member' : '/user/manager'

        let userInfoRes=await util.ajax({
            url:reqUrl,
            type:"GET"
        })

        let userInfo=userInfoRes.data.data
        console.log(userInfo)
        
        // save userinfo into localstorage
        for (let item in userInfo) {

            if (userInfo[item]===null)
            {
                userInfo[item]='';
            }
            localStorage.setItem(item, userInfo[item])
        }

        // 1 会员 2渠道
        let userType = parseInt(localStorage.userType)

        layer.open({
            content:"登录成功",
            btn:"确定",
            yes:()=>{
                if (this.gotoUrl){
                    window.location.href=this.gotoUrl;
                }else{
                    window.location.href="./pro.html";
                }
            }
        })
    }

    componentDidMount(){
        this.gotoUrl=util.getQuery().redirect_uri
        
    }

    render(){
        return (
            <div>
                <div id="login">
                    <img src="http://img0.rongsue.com/wechat/logo_h5.png" alt="" />
                    <input type="text" className="text" placeholder="请输入手机号" style={{borderColor:(this.state.username_valid)?'#E6E6E6':'#FF0000'}} value={this.state.username} onChange={this.usernameChange.bind(this)} maxLength="11"/>
                    <input type="password" className="text" placeholder="请输入密码" style={{borderColor:(this.state.password_valid)?'#E6E6E6':'#FF0000'}} value={this.state.password} onChange={this.passwordChange.bind(this)} maxLength="16"/>
                    <input type="button" className="btn" value="登录" onClick={this.beforeLogin.bind(this)}/>
                    <div className="linkbox">
                        <a href="./reg.html" className="fr">没有账号，<span>注册&gt;&gt;</span></a>
                        <a href="javascript:;" style={{display:"none"}}>忘记密码?</a>
                    </div>
                    <div style={{height:"30px"}}></div>
                </div>
            </div>
        )
    }
}


ReactDom.render(<Login />,document.getElementById("app"));